package utils

import (
	"errors"
	"golang.org/x/crypto/bcrypt"
	"regexp"
)

// ValidateCode 验证码验证
func ValidateCode(inputCode, storedCode string) (bool, error) {
	if storedCode == "" {
		return false, errors.New("验证码已过期或不存在")
	}

	if inputCode != storedCode {
		return false, errors.New("验证码错误")
	}
	return true, nil
}

// CheckPasswordHash 检查密码是否正确
func CheckPasswordHash(password, hash string) error {
	return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
}

// VerifyEmail 验证邮箱
func VerifyEmail(email string) bool {
	reg := regexp.MustCompile("^[A-Za-z0-9\\p{Han}]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")
	return reg.MatchString(email)
}

func VerifyIDCard(idCard string) bool {
	reg := regexp.MustCompile("^([1-6][1-9]|50)\\d{4}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dXx]$")
	return reg.MatchString(idCard)
}

func VerifyPassword(password string) bool {
	reg := regexp.MustCompile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\\W).{9,}$")
	return reg.MatchString(password)
}

// BcryptPassword 生成 Bcrypt 加密后的密码
func BcryptPassword(str string) (string, error) {
	hash, _ := bcrypt.GenerateFromPassword([]byte(str), bcrypt.DefaultCost)
	err := bcrypt.CompareHashAndPassword(hash, []byte(str))

	return string(hash), err
}
